package repository

import (
	"errors"
	"gorm.io/gorm"
	"shop-bean/model"
	"shop-bean/vo"
	"shop-common/utils/queryWrapper"
)

type ICategoryRepository interface {
	Find(db *gorm.DB, shopId int, _type int) (list []*vo.CategoryVO, err error)
	FindById(db *gorm.DB, id uint) (category *model.Category, err error)
	FindByParentId(db *gorm.DB, parentId uint) (list []*vo.CategoryVO, err error)
	FindOne(db *gorm.DB, pair *queryWrapper.WherePair) (category *model.Category, err error)
	Create(db *gorm.DB, category *model.Category) error
	Delete(db *gorm.DB, id uint) error
	Updates(db *gorm.DB, id uint, columns map[string]interface{}) error
}

type CategoryRepository struct {
}

func NewCategoryRepository() ICategoryRepository {
	return &CategoryRepository{}
}

func (r *CategoryRepository) Find(db *gorm.DB, shopId, _type int) (list []*vo.CategoryVO, err error) {
	err = db.Model(&model.Category{}).Where("shop_id = ?", shopId).Where("type = ?", _type).Order("seq desc").Find(&list).Error
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, err
	}
	return list, nil
}

func (r *CategoryRepository) Create(tx *gorm.DB, category *model.Category) error {
	return tx.Create(&category).Error
}

func (r *CategoryRepository) FindById(db *gorm.DB, id uint) (category *model.Category, err error) {
	return category, db.First(&category, id).Error
}

func (r *CategoryRepository) FindByParentId(db *gorm.DB, parentId uint) (list []*vo.CategoryVO, err error) {
	return list, db.Model(&model.Category{}).Where("parent_id = ?", parentId).Find(&list).Error
}

func (r *CategoryRepository) FindOne(db *gorm.DB, pair *queryWrapper.WherePair) (category *model.Category, err error) {
	tx := db.Model(&model.Category{})
	tx = queryWrapper.ReuseWherePair(tx, pair)
	return category, tx.First(&category).Error
}

func (r *CategoryRepository) Delete(db *gorm.DB, id uint) error {
	return db.Delete(&model.Category{}, id).Error
}

func (r *CategoryRepository) Updates(db *gorm.DB, id uint, columns map[string]interface{}) error {
	return db.Model(&model.Category{}).Where("category_id = ?", id).Updates(columns).Error
}
